package org.dataframework.security.core;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.Select;
import org.dataframework.security.core.context.RuleContextHolder;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: LiuCf
 * @Email: 1316640406@qq.com
 * @Date: 2021/7/3 14:10
 */
public class JdbcStatementInspector implements StatementInspector {
    private Logger logger = LoggerFactory.getLogger(JdbcStatementInspector.class);

    @Override
    public String inspect(String sql) {
        try {
            Statement statement = CCJSqlParserUtil.parse(sql);
            if (statement instanceof Select) {
                RuleAppliers.apply(statement, RuleContextHolder.get().getRules());
                return statement.toString();
            }
        } catch (JSQLParserException e) {
            logger.error("解析出错===>{}", e.getCause());
        }

        return sql;
    }
}
